package com.nxj.servlet;

import com.nxj.factory.HandlerMappingGenerator;
import com.nxj.pojo.Handler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;

public class DefaultServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Handler handler = HandlerMappingGenerator.mapHandler(req.getRequestURI());
        if (handler == null)
            throw new RuntimeException("error 404");
        Object[] paramValues = new Object[handler.getMethod().getParameterCount()];

        if (handler.getSecuritys() != null && !Arrays.asList(handler.getSecuritys()).contains(req.getParameter("username"))) {
            resp.sendRedirect("/error.html");
            return;
        }
        req.getParameterMap().forEach((s, strings) -> {
            if (handler.getParamIndexMap().containsKey(s)) paramValues[handler.getParamIndexMap().get(s)] = strings[0];
        });

        if (handler.getParamIndexMap().containsKey(HttpServletResponse.class.getSimpleName()))
            paramValues[handler.getParamIndexMap().get(HttpServletRequest.class.getSimpleName())] = req;
        if (handler.getParamIndexMap().containsKey(HttpServletRequest.class.getSimpleName()))
            paramValues[handler.getParamIndexMap().get(HttpServletResponse.class.getSimpleName())] = resp;

        try {
            handler.getMethod().invoke(handler.getController(), paramValues);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        resp.sendRedirect("/index.html");
    }
}
